/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { useContext, useEffect, useState } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import type { ViewStyle } from 'react-native';
import { useBreakpointValue, useHeightBreakpointValue } from '@hadss/react_native_adaptive_layout';
import Context from '../../Context';

const Counter = () => {
  const { isRecording } = useContext(Context);
  const [seconds, setSeconds] = useState(0);

  useEffect(() => {
    const timer = setInterval(() => {
      if (!isRecording) {
        clearInterval?.(timer);
      }
      setSeconds(prev => prev + 1);
    }, 1000)
    return () => {
      setSeconds(0);
      clearInterval?.(timer);
    }
  }, [])

  const formatTime = (totalSeconds: number) => {
    const hours = Math.floor(totalSeconds / 3600);
    const minutes = Math.floor(totalSeconds / 60);
    const seconds = totalSeconds % 60;
    let hh = hours.toString().padStart(2, '0');
    let mm = minutes.toString().padStart(2, '0');
    let ss = seconds.toString().padStart(2, '0');
    return `${hh}:${mm}:${ss}`;
  };

  const isSmall = useHeightBreakpointValue<boolean>({
    base: false,
    sm: true,
    md: true,
    lg: false
  })

  /** 计时器显示位置 */
  const counter = useBreakpointValue<ViewStyle>({
    base: isSmall ? {
      position: 'absolute',
      top: 64,
      width: '100%',
      zIndex: 5
    } : {
      position: 'absolute',
      top: 84,
      width: '100%',
      zIndex: 5
    },
    md: {
      position: 'absolute',
      top: 54,
      width: '100%',
      zIndex: 5
    }
  })
  return (
    <View style={counter}>
      {
        isRecording && (
          <Text style={style.text}>{formatTime(seconds)}</Text>
        )
      }
    </View>
  )
}

const style = StyleSheet.create({
  text: {
    fontSize: 14,
    lineHeight: 20,
    color: 'rgba(255, 255, 255, 1)',
    textAlign: 'center'
  }
})

export default Counter;
